<?php

namespace app\api\controller;

use app\admin\model\Sales;
use app\admin\model\SalesDetail;
use app\admin\model\SystemUploadfile;
use app\admin\model\Users;
use think\facade\Cache;
use think\facade\Request;

class Task
{
    /**
     * 前台月排行榜刷新任务
     * 定时任务每5分钟请求一次，每次缓存6分钟
     */
    public function getRanking()
    {
        $data = ranking(2,10);
        foreach ($data as $k => $v){
            $return = 0;
            $res = Sales::where('uid', $v['uid'])->select();
            foreach ($res as $a => $b){
                $detail_num = SalesDetail::where('sales_id', $b['id'])->count();
                $return += $detail_num - 1;
            }
            $data[$k]['sales'] = count($res);
            $data[$k]['return'] = $return;
            $head_img_id = Users::where('uid', $v['uid'])->value('head_img_id');
            $data[$k]['head_img'] = SystemUploadfile::where('id', $head_img_id)->value('url') ?: Request::domain().'/upload/20200718/head_img.png';
            unset($data[$k]['num']);
        }
        Cache::set('index_month_ranking', $data, 360);
        return 'success';
    }

    /**
     * 后台排行榜刷新任务
     * 定时任务每5分钟请求一次,每次缓存6分钟
     */
    public function adminRanking($type = 0, $length = 10, $month = null){
        $users = Users::where('status',0)->field('uid,true_name')->select();
        foreach ($users as $k => $user){
            $num = 0;
            $sales = Sales::where('uid', $user->uid)->select();
            foreach ($sales as $sale){
                if (in_array($type, [0,1])){
                    $num += SalesDetail::where('sales_id', $sale->id)->whereDay('create_time', $type ? 'yesterday' : 'today')->count();
                }else{
                    if (is_null($month)){
                        $num += SalesDetail::where('sales_id', $sale->id)->whereMonth('create_time')->count();
                    }else{
                        $num += SalesDetail::where('sales_id', $sale->id)->whereMonth('create_time', $month)->count();
                    }
                }
            }
            $users[$k]['num'] = $num;
        }
        $users = $users->toArray();
        foreach ($users as $k => $v){
            if (!$v['num']){
                unset($users[$k]);
            }
        }
        $num = array_column($users,'num');
        array_multisort($num, SORT_DESC, $users);
        if (count($users) < $length){
            $length = count($users);
        }
        $users = array_slice($users,0, $length);
        Cache::set('admin_ranking_type_'.$type, $users, 360);
        return 'success';
    }
}